package developer.zyk.starter.controllers.global;

import cn.hutool.json.JSONUtil;
import developer.zyk.global.common.Result;
import developer.zyk.global.upload.FileOssTemplate;
import developer.zyk.global.upload.entity.UploadResult;
import developer.zyk.global.upload.upload.PathHelper;
import developer.zyk.global.user.bo.UserInfo;
import developer.zyk.starter.controllers.global.vo.FileUploadVO;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author zhangyongkang
 * @time 2025/5/15 19:45
 * @description
 */
@RestController
@RequestMapping("upload")
public class FileController {
    @Resource
    private FileOssTemplate fileOssTemplate;

    @PostMapping("file")
    public Result<FileUploadVO> updateFile(@RequestParam("file") MultipartFile file, @RequestParam("userInfo") String userInfo, @RequestParam("uploadType") String uploadType) throws IOException {
        InputStream inputStream = file.getInputStream();
        String name = file.getOriginalFilename();
        String path = PathHelper.getPath(Optional.ofNullable(uploadType).orElse("{}"), name, JSONUtil.toBean(userInfo, UserInfo.class));
        UploadResult uploadResult = fileOssTemplate.uploadWithInputStream(inputStream,
                path, name);

        return Result.success(
                new FileUploadVO(
                        uploadResult.getFileId(),
                        uploadResult.getUrl()
                )
        );
    }
}
